var startUpSound = new Audio('sound/startup.mp3');


var needsLoading = true;

var device = {
  input:'mouse',
  size:{},
  supported:true
}

function getDeviceSize(){
  device.size.height = window.screen.height;
  device.size.width = window.screen.width;

  console.log("DEVICE SIZE IS "+device.size.width+" AND "+device.size.height);
}

getDeviceSize();

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
 // some code..
 device.input = 'touch';

 if (device.size.width < 900 && device.size.height < 900) {
   //Unsupported
   device.supported = false;
   needsLoading = false;
 }

}
console.log("DEVICE SUPPORT IS "+device.supported);

console.log("INPUT IS "+device.input);



//Animate Tasks
var tasks = {};
/*tasks.action = [
  'Loading',
  'Generating',
  'Deleting',
  'Cutting',
  'Connecting',
  'Pushing',
  'Crashing',
  'Installing',
  'Pulling',
  'Swimming',
  'Moving',
  'Watching',
  'Following',
  'Liking',
  'Processing',
  'Winning',
  'Twitting',
  'Posting',
  'Judging',
  'Cleaning',
  'Mopping',
  'Skipping',
  'Correcting',
  'Disliking',
  'Unfollowing',
  'Gathering',
  'Frying',
  'Asking',
  'Bypassing',
  'Stealing',
  'Hacking',
  'Petting'

];*/


/*tasks.subject = [
  'Kittens',
  'Bad pictures',
  'Ugly fonts',
  'Netflix',
  'Facebook fans',
  'Instagram follower',
  'Twitter',
  'Entire Google Database',
  'Selfies',
  'Cats',
  'Chihuahuas',
  'Fake news',
  'Whale screams',
  'Sunglasses',
  'Twelve legged dogs',
  'Grandmas fennel salad',
  'Colours',
  'Brussel Sprouts',
  'Irrelevant questions',
  'Preposterous ',
  'TV Shows',
  'Britney Spears',
  'Surroundings',
  'Security restrictions',
  'User webcam without consent',
  'User Credit card'
];*/


/*tasks.result = [
  'Successful',
  'Done',
  'Completed',
  'Nailed',
  'Cracked',
  'Too lazy to do it',
  'EO340 Permission Denied',
  'Warning, Dangerous contents',
  'Failed',
  'Not Found',
  'Fatal Error'
];*/

tasks.action = [
  '',
];

/*tasks.subject = [
  '生成项目中',
  '入侵支付宝数据库',
  '入侵微信支付数据库',
  '建立双向通信',
  '开始DDOS防护平台',
  '系统内核加载中',
  '入侵美国国防部',
  '夺取全球核弹控制权',
  '初始化磁盘',
  '初始化内存',
  'Alpaca OS加载中',
  '建立单向链路',
  '系统内核加载中',
  '控制A股',
  '打个飞机',
];*/

tasks.subject = [
  "批判一番",
  "我今天是作为一个长者跟你们讲",
  "你问我兹不兹次,我是兹次的",
  "提高自身的知识水平",
  "香港记者",
  "闷声大发财",
  "这是坠吼的",
  "不要想弄一个大新闻",
  "无可奉告",
  "不要“见着风，是得雨”啊",
  "我身经百战，见的多了",
  "谈笑风生",
  "苟利国家生死以",
  "岂因祸福避趋之",
  "西方哪个国家我没去过",
  "识得唔识得呀",
  "too simple啊，sometimes naïve!",
  "美国的华莱士",
  "比你们高到不知哪里去了",
  "我是身经百战了",
  "钦点你当下任特首",
  "背诵葛底斯堡演说",
  "中央已经决定了,就由你来当接班人",
  "你们还是另请高明吧，我实在也不是谦虚",
  "我有这个必要啊告诉你们一点，人生的经验",
  "I'm angry!我跟你讲，你们这样子啊，那不行的！",
  "是彭定康说的",
  "按照香港的基本法",
  "我干了这十几年也没有什么别的，大概三件事",
  "如果说还有一点什么成绩，就是军队一律不得经商",
  "很惭愧，就做了一点微小的工作",
  "你们给我搞的这本东西啊，Excited！",
  "一个人的命运啊，当然要靠自我奋斗，但是也要考虑到历史的行程",
  "中央都决定了，你来当总书记",
  "我说另请高明吧。我实在也不是谦虚",
  "而且这个效率efficiency…"
]

tasks.result = [
  //'成功',
  '',
];



var dosLoading = document.getElementById('dosLoading');
var taskList = document.getElementById('taskList');


var tasksLength = 120;
var iter = 0.3;
var taskSpeed = 1;
var count=0

function getRandomIndexOfArray(arrayLenght) {
  return Math.floor(Math.random() * Math.floor(arrayLenght));
}


function runTasks(){
  count++
  var list = document.createElement('li');
  var action = tasks.action[getRandomIndexOfArray(tasks.action.length)];
  var subject = tasks.subject[getRandomIndexOfArray(tasks.subject.length)];
  var resultIndex = getRandomIndexOfArray(tasks.result.length);
  var result = tasks.result[resultIndex];

  //var sentence = action+" "+subject+": "+result;
  var sentence = action+"-"+count+"s："+subject+" "+result;

  //list.appendChild(document.createTextNode("Task "+iter));

  list.appendChild(document.createTextNode(sentence));
  taskList.appendChild(list);

  //Highligh if if a failed task
  if (resultIndex > 7) {
    list.style.color = 'var(--yellow )';
  }
  dosLoading.scrollTop = dosLoading.scrollHeight;
  iter ++;
  if (iter < tasksLength) {
      //between 0 to 400 milliseconds
      var fakeWorkloadTime = (Math.random()*300)*taskSpeed;
      //goes faster the more it loads
      if(iter % 10){
        fakeWorkloadTime = fakeWorkloadTime/(iter/10);
      }else {
        fakeWorkloadTime = fakeWorkloadTime*(iter/10);
      }
      setTimeout(runTasks, fakeWorkloadTime);
  }else {
    var list = document.createElement('li');
    var br = document.createElement('br');
    list.appendChild(br)
    list.appendChild(br)
    list.appendChild(br)
    list.appendChild(document.createTextNode('你的生命在流逝，被续了'+count+'秒,进入系统中'));
    list.style.cssText="color: red";

    taskList.appendChild(list);
    setTimeout(fullyLoaded, 3000);
  }
}


function fullyLoaded(){
  dosLoading.parentNode.removeChild(dosLoading);
}


//Run loading if files need to be loaded, else show desktop
if (needsLoading) {
  runTasks();
}else {
  fullyLoaded();
}




//////

var installedApps = {};
var desktop = document.getElementById('desktop');

function bootOS(){
  updateOsHeader(OSDefaultMenu, 'finder');
  components.infoMenu();

  //Populate Desktop with icons and windows
  //这里主要是生成app对象（桌面app）
  for (var i = 0; i < apps.length; i++) {
    var a = apps[i];
    installedApps[a.info.name.id] = new App(i, a, 'small');
  }

  //Install headless apps
  //这里主要是生成app对象（头顶栏app）
  for (var i = 0; i < hiddenApps.length; i++) {
    var a = hiddenApps[i];
    installedApps[a.info.name.id] = new App(i, a, 'headless');
  }






  desktop.addEventListener("mousedown", deselectAll, false);
  desktop.addEventListener("click", selectFinder, false);

  //startUpSound.play();


  ///LOAD FINDER APPS/////////////

  //LOAD Chat
  var loadChatScripts = new ScriptLoader();
  loadChatScripts.require(['app.js'], 'apps/Chat/',
      function() {
          // Callback
          chatExe.start('OS');


  });




  //LOAD HEAVY STUFF IN BACKGROUND

  loadImage('img/icons/System/logo-main_black.svg');
  loadImage('img/patterns/Dark-1.png');
  loadImage('img/patterns/Dark-2.png');
  loadImage('img/patterns/Dotted-3.png');
  loadImage('img/patterns/Dotted-6.png');


  //loadImage('apps/Chat/img/CatProfilePic.svg');
  loadImage('apps/Chat/img/alpaca.png');
  loadVideo('apps/WhoRU/img/0.intro.mp4');
  loadVideo('apps/Portfolio/projects/canberra/videos/JacobEmilyTurntable.mp4');
  loadVideo('apps/Portfolio/projects/wu/videos/FarView_BackForth.mp4');
  loadImage('apps/Info/About/img/profilePic_logo.png');
  loadImage('apps/Portfolio/projects/ebay/img/5.Personalisation_01.gif');
  loadImage('apps/Portfolio/projects/ebay/img/8.SightSearch_02.gif');
  loadImage('apps/Portfolio/projects/ebay/img/12.Product_02.gif');


  function loadJSON(callback) {
     var xobj = new XMLHttpRequest();
         xobj.overrideMimeType("application/json");
     xobj.open('GET', 'apps/VirtualVandal/models/erik.json', true); // Replace 'my_data' with the path to your file
     xobj.onreadystatechange = function () {
           if (xobj.readyState == 4 && xobj.status == "200") {
             // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
             callback(xobj.responseText);
           }
     };
     xobj.send(null);
  };

  loadJSON(function(response) {
   console.log('3D READY');
  });




}




function displayUnsupportedMessage(){


  var body = document.getElementsByTagName("BODY")[0];
  //Delete everything
  while (body.firstChild) {
    if (body.firstChild.tagName === 'SCRIPT') {
      break;
    }
    body.removeChild(body.firstChild);
  }

  //Make App header
  var header = createElement('div','unsupported_mobileHeader', undefined, undefined);
  body.appendChild(header);
  components.image('fullWidth', '', 'img/mobile/Mobile_Illustration.gif', header);



  //Make message
  var message = createElement('div','unsupported_mobileMessage', undefined, undefined);
  body.appendChild(message);
  components.image('centered-retina', '', 'img/mobile/Mobile_Message.gif', message);


  //Make links
  /*var tempLinks = '<a href="http://behance.net/erikbernacchi">behance.net/erikbernacchi</a><br>'+
                  '<a href="http://dribbble.com/erikbernacchi">dribbble.com/erikbernacchi</a><br>'+
                  '<a href="mailto:erik.bernacchi@gmail.com?subject=Hey Erik&body=Listen...">erik.bernacchi@gmail.com</a>';*/

  var tempLinks =  '<div style="color:white">不支持移动端查看，请用电脑端查看</div>'      
  var links = createElement('div','unsupported_mobileLinks', undefined, tempLinks);
  body.appendChild(links);


}




if (device.supported) {
  bootOS();
}else {
  displayUnsupportedMessage();
}



function shutDownSystem(){
  //make header container
  var body = document.getElementsByTagName("BODY")[0];
  circle = createElement('div','shutDownCircle', undefined, undefined);

  body.appendChild(circle);

  $(".shutDownCircle").attr("title","点击任意地方即可开机");

  TweenLite.to(circle, 0.9,{boxShadow:'inset 0 0 0 2000px rgb(255,255,255)',ease:Power3.easeOut,onComplete:function(){
    $(".shutDownCircle").click(function(){
        location.reload();
    });
  }});
}





///Reload functions below, we need a gateway that evaluates if user has been here
//before or start from scratch
